const amqp= require('amqplib');
const fs = require("fs");
const path = require('path');




// function getTimeStamp() {
//     return new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14);
// }
// const port = new SerialPort({
//   path: 'COM11', // 串口路径
//   baudRate: 921600 // 波特率
// });

saveMessages


let serialDataCount = 0;
let sendchannel:any;
let comchannel:any;
// let timestamp ;
const queue = 'electron';
const exchange = 'WHUelectron';
const exchangeType = 'direct';
const connection = await amqp.connect('amqp://localhost');

sendchannel = await initChannelsend();

let messageCache:string[] = [];//缓存消息
let currentExperimentName:string = 'default';//储存实验名称


async function initChannelsend(){
         let channel:any;
       
        channel = await connection.createChannel();
        await channel.assertExchange(exchange, exchangeType, { durable: true });
        console.log(`交换机 "${exchange}" 已声明`);
        await channel.assertQueue(queue, { durable: true });
        console.log(`队列 "${queue}" 已创建或已存在`);
        await channel.bindQueue(queue, exchange, '');
        console.log(`队列 "${queue}" 已绑定到交换机 "${exchange}"`);
    
        return channel;
    }

async function initChannelcom(){
  
        let channel:any;
        channel = await connection.createChannel();
        await channel.assertExchange(exchange, exchangeType, { durable: true });
        console.log(`com交换机 "${exchange}" 已声明`);
        await channel.assertQueue(queue, { durable: true });
        console.log(`队列 "${queue}" 已创建或已存在`);
        await channel.bindQueue(queue, exchange, '#');
        console.log(`队列 "${queue}" 已绑定到交换机 "${exchange}"`);
    
        return channel;
    }


export async function sendmsg(data:any){
    try {
       
    
        // 发送持久化消息
        let hexmsg = "";
        // console.log('接收到数据:', serialDataCount,":",Buffer.from(data));
        // if(data[0].toString(16).toUpperCase() == "FF"){
            for(let i = 0; i < data.length; i++){
                hexmsg +=data[i].toString(16).toUpperCase().padStart(2, '0')
                // console.log()
            }
        serialDataCount++;
        console.log(`接收到数据包[${serialDataCount}]:`, Buffer.from(data));
        sendchannel.publish(exchange, '', Buffer.from(hexmsg), {persistent: true});

        console.log('消息发送成功');


        }catch (error) {
            console.log('消息发送失败:',error);
        }
    }

export async function consumermsg(){
    try {
        comchannel = await initChannelcom();
        console.log('等待消息接收');
        
        let messageCount = 0;
        
        comchannel.consume(queue, (msg:any) => {
            if (!msg) return;
                
                const messageString = msg.content.toString(); // 转换为字符串
                messageCount++;                          
                console.log(`接收到消息: ${messageString}, 当前消息计数: ${messageCount}`);
                // const channelData = parseSerialData(messageString);      
                // console.log('解析数据:', channelData);               
                console.log(1)

                messageCache.push(messageString);// 缓存消息到内存
                console.log(2)

                // const experimentName = localStorage.getItem('experimentName') || 'default';
                
                // // const timestamp1 = getTimeStamp();
                // fs.appendFileSync("./"+experimentName + ".txt", messageString );

                // const fileName = `data_${experimentName}.txt`;
                //  // 保存数据到文件。(__dirname,)
                // const filePath = path.join( "./",fileName);
                // fs.appendFileSync(filePath, messageString + '\n'); 
                // console.log(3)

                comchannel.ack(msg); 
        })

        }catch (error) {
            console.log('消息接受失败:',error);
        }
    };

//设置实验名称
export function setExperimentName(name: string) {
  currentExperimentName = name;
}

export function saveMessages() {
    const filePath = path.join( "./",`${currentExperimentName}.txt`);
    fs.writeFileSync(filePath, messageCache.join(''),{ flag:'w'});//{ flag:'w'}覆盖写入
    console.log('数据保存成功');
    messageCache = [];
}
